package org.example.app.bean;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.HashMap;
import java.util.Map;

/**
 * 品类分析累加器 - 用于Flink聚合操作
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class CategoryAnalysisAccumulator {
    
    // 品类基本信息
    public String categoryId;
    public String categoryName;
    public String parentCategoryId;
    public String parentCategoryName;
    
    // 累计度量值
    public Double totalSalesAmount = 0.0;
    public Long totalSalesCount = 0L;
    public Long productCount = 0L;
    public Long brandCount = 0L;
    public Long shopCount = 0L;
    public Double totalPrice = 0.0;
    public Integer count = 0;
    
    // 属性统计
    public Map<String, Long> colorCounts = new HashMap<>();
    public Map<String, Long> sizeCounts = new HashMap<>();
    public Map<String, Long> materialCounts = new HashMap<>();
    public Map<String, Long> brandCounts = new HashMap<>();
    public Map<String, Long> shopCounts = new HashMap<>();
    
    // 价格统计
    public Double minPrice = Double.MAX_VALUE;
    public Double maxPrice = Double.MIN_VALUE;
    
    // 窗口时间信息
    public Long windowStart;
    public Long windowEnd;
    
    /**
     * 重置累加器
     */
    public void reset() {
        this.totalSalesAmount = 0.0;
        this.totalSalesCount = 0L;
        this.productCount = 0L;
        this.brandCount = 0L;
        this.shopCount = 0L;
        this.totalPrice = 0.0;
        this.count = 0;
        this.colorCounts.clear();
        this.sizeCounts.clear();
        this.materialCounts.clear();
        this.brandCounts.clear();
        this.shopCounts.clear();
        this.minPrice = Double.MAX_VALUE;
        this.maxPrice = Double.MIN_VALUE;
    }
    
    /**
     * 计算平均价格
     */
    public Double calculateAvgPrice() {
        if (totalSalesCount > 0) {
            return totalSalesAmount / totalSalesCount;
        }
        return 0.0;
    }
    
    /**
     * 获取最热门的属性值
     */
    public String getTopAttribute(Map<String, Long> attributeCounts) {
        return attributeCounts.entrySet().stream()
                .max(Map.Entry.comparingByValue())
                .map(Map.Entry::getKey)
                .orElse("unknown");
    }
    
    /**
     * 计算属性集中度
     */
    public Double calculateConcentration(Map<String, Long> attributeCounts) {
        if (attributeCounts.isEmpty()) return 0.0;
        
        long total = attributeCounts.values().stream().mapToLong(Long::longValue).sum();
        if (total == 0) return 0.0;
        
        long maxCount = attributeCounts.values().stream().mapToLong(Long::longValue).max().orElse(0L);
        return maxCount * 100.0 / total;
    }
}